<template>
  <div class="register-container">
    <NavBar>
      <template #default>
        注册
      </template>
    </NavBar>

    <!-- 注册表单 -->
    <div class="register-section">
      <div class="section-header">用户注册</div>
      <el-form :model="form" :rules="rules" ref="registerForm" label-width="100px">
        <!-- 头像上传 -->
         <el-form-item label="头像" prop="avatarFile">
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :auto-upload="false"
      :on-change="handleAvatarChange"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="form.avatarUrl" :src="form.avatarUrl" class="avatar">
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
    <div class="upload-tips">支持JPG/PNG格式，大小不超过2MB</div>
  </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input
            v-model="form.userName"
            placeholder="请输入用户名"
            clearable
          />
          <div class="input-tips">
            3-20位字符，支持中文、字母、数字、下划线
          </div>
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input
            v-model="form.mobile"
            placeholder="请输入手机号"
            clearable
          />
        </el-form-item>

        <el-form-item label="密码" prop="userPassword">
          <el-input
            v-model="form.userPassword"
            placeholder="6-100位字符"
            type="password"
            show-password
            clearable
          />
          <div class="password-tips">
            密码长度需6-100位字符
          </div>
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="form.confirmPassword"
            placeholder="请再次输入密码"
            type="password"
            show-password
            clearable
          />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="form.email"
            placeholder="请输入邮箱"
            clearable
          />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>

    <!-- 注册按钮 -->
    <div class="register-btn" @click="handleRegister">
      立即注册
    </div>

    <!-- 登录链接 -->
    <div class="login-link">
      已有账号？<span @click="goToLogin">去登录</span>
    </div>
  </div>
</template>

<script setup>
import NavBar from '../../components/common/NavBar.vue';
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import { UserRegister } from '@/api/UserApi';

const router = useRouter();
const registerForm = ref(null);

// 表单数据
const form = ref({
  avatarFile: null,
  avatarUrl: '',
  userName: '',
  mobile: '',
  userPassword: '',
  confirmPassword: '',
  email: '',
  gender: 1
});

// 头像上传处理
const beforeAvatarUpload = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传JPG/PNG格式的图片!');
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!');
  }

  return isImage && isLt2M;
};

// 修改头像处理函数
const handleAvatarChange = (file) => {
  // 只保存文件对象和本地预览URL，不上传
  form.value.avatarFile = file.raw;
  form.value.avatarUrl = URL.createObjectURL(file.raw);
};

// 验证规则
const validateUserName = (rule, value, callback) => {
  const reg = /^[\u4e00-\u9fa5a-zA-Z0-9_]{3,20}$/;  // 允许中文、字母、数字、下划线
  if (!value) {
    callback(new Error('请输入用户名'));
  } else if (!reg.test(value)) {
    callback(new Error('用户名格式不正确（3-20位中文、字母、数字或下划线）'));
  } else {
    callback();
  }
};

const validateMobile = (rule, value, callback) => {
  const reg = /^1[3-9]\d{9}$/;
  if (!value) {
    callback(new Error('请输入手机号'));
  } else if (!reg.test(value)) {
    callback(new Error('手机号格式不正确'));
  } else {
    callback();
  }
};

const validatePassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入密码'));
  } else if (value.length < 6) {
    callback(new Error('密码长度至少6位'));
  } else {
    callback();
  }
};

const validateConfirmPassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请确认密码'));
  } else if (value !== form.value.userPassword) {
    callback(new Error('两次输入密码不一致'));
  } else {
    callback();
  }
};

const validateEmail = (rule, value, callback) => {
  const reg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  if (!value) {
    callback(new Error('请输入邮箱'));
  } else if (!reg.test(value)) {
    callback(new Error('邮箱格式不正确'));
  } else {
    callback();
  }
};

const rules = {
  userName: [
    { validator: validateUserName, trigger: 'blur' }
  ],
  mobile: [
    { validator: validateMobile, trigger: 'blur' }
  ],
  userPassword: [
    { validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  email: [
    { validator: validateEmail, trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ]
};

// 提交注册
const handleRegister = async () => {
  try {
    await registerForm.value.validate();

    const formData = new FormData();
    if (form.value.avatarFile) {
      formData.append('avatarFile', form.value.avatarFile);
    }
    formData.append('userName', form.value.userName);
    formData.append('userPassword', form.value.userPassword);
    formData.append('mobile', form.value.mobile);
    formData.append('email', form.value.email);
    formData.append('gender', form.value.gender);

    const response = await UserRegister(formData);
    console.log(response);

    if (response.code === 1) {
      ElMessage.success(response.msg || '注册成功');
      // 跳转到登录页
      setTimeout(() => router.push('/login'), 1500);
    } else {
      ElMessage.error(response.msg || '注册失败');
    }
  } catch (error) {
    console.error('注册失败:', error);
    const errorMsg = error.response?.msg ||
                    error.response?.message ||
                    error.message ||
                    '注册失败';
    ElMessage.error(errorMsg);
  }
};

// 跳转到登录页
const goToLogin = () => {
  router.push('/login');
};
</script>

<style scoped>
.register-container {
  background-color: #fff;
  min-height: 100vh;
  padding-bottom: 60px;
}

.register-section {
  background-color: #fff;
  margin: 10px;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  margin-bottom: 15px;
}

.section-header {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.register-btn {
  margin: 20px 15px;
  padding: 12px 0;
  background-color: #ff5000;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
}

.register-btn:active {
  opacity: 0.9;
}

.input-tips,
.password-tips,
.upload-tips {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.el-form {
  padding-top: 10px;
}

.el-form-item {
  margin-bottom: 15px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
}

.login-link {
  text-align: center;
  font-size: 14px;
  color: #666;
  margin-top: 20px;
}

.login-link span {
  color: #ff5000;
  cursor: pointer;
}
</style>